import { App, Seed } from "@/seed-application/types"

export const getSeedModules = (seeds: Record<string, Seed>) => {
  const ret = {}
  if(!seeds) return ret

  for(const i in seeds) {
    const seed = seeds[i]
    const seedName = seed.name
    const children = []
    const actions = seed.actions || getDefaultActions()
    for(const j in actions) {
      const action = actions[j]
      children.push({value: `${seedName}:${action.name}`, label: action.label || action.name})
    }
    ret[seedName] = {label: `${seed.label}管理`, children}
  }

  return ret
}

export const getLibModules = async (libs: String[]) => {
  const ret = {}
  if(!libs) return ret

  for(const i in libs) {
    const lib = libs[i]
    const modules = []
    if('uaa' == lib) {
      const files = import.meta.glob('@/uaa/**/index.ts')
      for (const path in files) {
        const file: any = await files[path]()
        modules.push(file.default)
      }
    }

    for(const i in modules) {
      const module = modules[i]
      const moduleName = module.name
      const children = []
      for(const j in module.actions) {
        const action = module.actions[j]
        children.push({value: `${moduleName}:${action.name}`, label: action.label || action.name})
      }
      ret[moduleName] = {label: `${module.label}管理`, children}
    }
  }

  return ret
}

export const getActions = async (app: App) => {
  const ret = {}
  const appSeedModules = getSeedModules(app.seeds)
  for(const moduleName in appSeedModules) ret[moduleName] = appSeedModules[moduleName]

  const appLibModules = await getLibModules(app.libs)
  for(const moduleName in appLibModules) ret[moduleName] = appLibModules[moduleName]

  for(const i in app.micros) {
    const micro = app.micros[i]
    const microSeedModules = getSeedModules(micro.seeds)
    for(const moduleName in microSeedModules) {
      const module = microSeedModules[moduleName]
      for(const j in module.children) {
        const action = module.children[j]
        action.value = `${micro.name}:${action.value}`
      }
      ret[`${micro.name}.${moduleName}`] = module
    }

    const microLibModules = getLibModules(micro.libs)
    for(const moduleName in microLibModules) {
      const module = microLibModules[moduleName]
      for(const j in module.children) {
        const action = module.children[j]
        action.value = `${micro.name}:${action.value}`
      }
      ret[`${micro.name}.${moduleName}`] = module
    }
  }
  
  return ret
}

const getDefaultActions = () => {
  return [
    {name: 'page', label: '分页列表', checkAction: true, checkData: true},
    {name: 'save', label: '保存'},
    {name: 'update', label: '编辑'},
    {name: 'detail', label: '详情', checkAction: true, checkData: true},
    {name: 'remove', label: '删除'},
    {name: 'importExcel', label: '导入'},
    {name: 'exportExcel', label: '导出', checkAction: true, checkData: true}
  ]
}